from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLineEdit, QPushButton, QFrame, QMessageBox
from PyQt5.QtCore import pyqtSignal, Qt
from widgets.avatar_label import AvatarLabel
from auth.register_dialog import RegisterDialog
from widgets.countdown_button import CountdownButton
from db_utils import find_user_by_account

class LoginWidget(QWidget):
    login_success = pyqtSignal(dict)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setStyleSheet('background:#f5f6f7;')

        # 外层居中
        outer_layout = QVBoxLayout(self)
        outer_layout.setAlignment(Qt.AlignCenter)
        container = QFrame()
        container.setFixedSize(420, 380)
        container.setStyleSheet('background:white;border-radius:8px;')
        outer_layout.addWidget(container)

        layout = QVBoxLayout(container)
        layout.setContentsMargins(24,24,24,24)

        self.avatar = AvatarLabel(100)
        self.btn_change_avatar = QPushButton('上传头像'); self.btn_change_avatar.clicked.connect(self._upload_avatar)
        av_h = QHBoxLayout(); av_h.addStretch(); av_h.addWidget(self.avatar); av_h.addWidget(self.btn_change_avatar); av_h.addStretch()
        layout.addLayout(av_h)

        self.le_account = QLineEdit(); self.le_account.setPlaceholderText('账号 (手机号/用户名)')
        self.le_password = QLineEdit(); self.le_password.setPlaceholderText('密码'); self.le_password.setEchoMode(QLineEdit.Password)
        layout.addWidget(self.le_account)
        layout.addWidget(self.le_password)

        btn_h = QHBoxLayout()
        self.btn_login = QPushButton('登录'); self.btn_login.clicked.connect(self._on_login)
        self.btn_register = QPushButton('注册'); self.btn_register.clicked.connect(self._on_register)
        self.btn_reset = QPushButton('重置密码'); self.btn_reset.clicked.connect(self._on_reset)
        btn_h.addWidget(self.btn_login); btn_h.addWidget(self.btn_register); btn_h.addWidget(self.btn_reset)
        layout.addLayout(btn_h)

        self._countdown = CountdownButton()
        self._countdown.hide()  # 可选，增加登录前倒计时限制逻辑

    def _upload_avatar(self):
        from PyQt5.QtWidgets import QFileDialog
        path, _ = QFileDialog.getOpenFileName(self, '选择头像', '.', 'Images (*.png *.jpg *.jpeg)')
        if path:
            self.avatar.set_avatar(path)

    def _on_register(self):
        dlg = RegisterDialog(self)
        dlg.exec_()

    def _on_reset(self):
        QMessageBox.information(self, '重置密码', '请联系管理员或使用注册手机号重置（示例未实现）')

    def _on_login(self):
        account = self.le_account.text().strip()
        pwd = self.le_password.text().strip()

        if not account or not pwd:
            QMessageBox.warning(self, '错误', '请输入账号和密码')
            return

        # 查询用户
        row = find_user_by_account(account)
        if not row:
            QMessageBox.warning(self, '错误', '账号不存在')
            return

        if pwd != row[4]:  # 假设 row[4] 是密码字段
            QMessageBox.warning(self, '错误', '密码错误')
            return

        # 登录成功，发射信号
        user_info = {
            'id': row[0],
            'username': row[1],
            'phone': row[2],
            'account': row[3],
            'avatar': row[5]
        }
        QMessageBox.information(self, '登录', f'登录成功，欢迎 {row[1]}')
        self.login_success.emit(user_info)

